﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Talk.Net.Server
{
	/// <summary>
	/// Interaction logic for AudioVisualizer.xaml
	/// </summary>
	public partial class AudioVisualizer : UserControl
	{
		private byte[] Audio;
		private int AudioLength;
		private int MaxAmplitude = 128;
		//private int RenderCount = 0;

		PathFigure figure;
		PathGeometry geometry;
		PathSegmentCollection segments;
		PathFigureCollection figures;

		public AudioVisualizer()
		{
			InitializeComponent();
			this.SizeChanged += new SizeChangedEventHandler(AudioVisualizer_SizeChanged);
		}

		void AudioVisualizer_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			Render();
		}

		public void SetAudio(byte[] audio)
		{
			Audio = audio;
			if (Audio.Length != AudioLength)
			{
				Setup(Audio.Length);
			}
			AudioLength = Audio.Length;
			Render();
		}

		public void Setup(int AudioLength)
		{
			double startX, startY;

			startX = 0;
			startY = this.ActualHeight / 2;

			geometry = new PathGeometry();
			segments = new PathSegmentCollection();
			figures = new PathFigureCollection();

			figure = new PathFigure();
			figure.StartPoint = new Point(startX, startY);

			for (int i = 0; i < AudioLength; i++)
			{
				LineSegment segment = new LineSegment();
				double segmentX = ((double)(i + 1) / (double)AudioLength) * this.ActualWidth;
				double segmentY = 0;
				segment.Point = new Point(segmentX, startY + segmentY);
				segments.Add(segment);
			}

			figure.Segments = segments;
			figures.Add(figure);
			geometry.Figures = figures;
		}

		public void Render()
		{
			if (ActualHeight == 0 || ActualWidth == 0) 
				return;

			if (AudioLength ==0)
				return;

			//RenderCount++;
			//TestLabel.Content = ActualWidth + "," + ActualHeight + " - (" + RenderCount + ")";

			figure.StartPoint = new Point(0, ActualHeight / 2);
			
			for (int i = 0; i < AudioLength; i++)
			{
				double segmentX = ((double)(i+1) / (double)AudioLength) * this.ActualWidth;
				double audioValue = Audio[i];

				// because i don't understand pcm format yet. =)
				audioValue = audioValue - 128;

				double segmentY = (audioValue / (double)MaxAmplitude) * (this.ActualHeight / 2);

				LineSegment tempSegment = ((LineSegment)segments[i]);
				tempSegment.Point = new Point(segmentX, segmentY+(ActualHeight/2));
			}

			AudioPath.Data = geometry;
		}
	}
}
